package com.java.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.java.model.*;
import com.java.service.*;
import com.java.utils.CommonUtils;
import com.java.utils.JsonBody;
import com.java.utils.PageList;
import com.java.utils.ResponseUtil;
import com.java.utils.StringUtil;;

@RestController
@RequestMapping("/news")
public class NewsController {
	private NewsService newsService;

	public NewsService getNewsService() {
		return newsService;
	}

	@Autowired
	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}

	@Autowired
	private NewsTypeService newstypeService;

	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;

	@CrossOrigin(origins = "*")
	@ResponseBody
	@RequestMapping("getbyid")
	public JsonBody getbyid(int id) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("add", newsService.GetByID(id));
		map.put("newstype", newstypeService.Get());
		return Util.SetData(map);
	}

	@CrossOrigin(origins = "*")
	@ResponseBody
	@RequestMapping("add")
	public JsonBody add(@RequestBody News n) {
			int count=0;
			if(n.getId()==0)
				count = newsService.Add(n);
			else
				count=newsService.Edit(n);
			if(count>0)
				return Util.SetMap("保存成功", true);
			else
				return Util.SetMap("保存失败", false);
	}

	@CrossOrigin(origins = "*")
	@ResponseBody
	@RequestMapping("list")
	public JsonBody list(News n) {
		List<News> ns=newsService.Get(n);
		for(News news:ns)
			news.setNewstype(newstypeService.GetByID(news.getId()));
		return Util.SetData(ns);
	}


	@CrossOrigin(origins = "*")
	@ResponseBody
	@RequestMapping("zan")
	public JsonBody Zan(int id) {
		if(request.getHeader("X-Token")==null)
			return Util.SetMap("请先登录",false);
		if(newsService.EditZan(id)>0)
			return Util.SetMap("点赞成功",true);
		else
			return Util.SetMap("点赞失败",false);
	}


	@CrossOrigin(origins = "*")
	@ResponseBody
	@RequestMapping("del")
	public JsonBody del(int id) {
		if(newsService.Del(id)>0)
			return Util.SetMap("删除成功", true);
		else
			return Util.SetMap("删除失败", false);
	}


}
